<template>
  <commonDialog
    :show="homeStore.isLogin"
    width="1000px"
    :buttons="dialogConfig.buttons"
    :show-cancel="false"
    @close="closeDialog"
  >
    <div class="dialog-panel">
      <div class="bg">
        <img src="@/assets//login_bg.png" alt="" />
      </div>
      <el-form
        class="login-register"
        ref="formDataRef"
        :model="formData"
        :rules="rules"
        @submit.prevent
        :validate-on-rule-change="false"
      >
        <div class="tab-panel">
          <div :class="currentOpType == 1 ? 'active' : ''" @click="showPanel(1)">登录</div>
          <el-divider direction="vertical" />
          <div :class="currentOpType == 0 ? 'active' : ''" @click="showPanel(0)">注册</div>
        </div>
        <el-form-item prop="email">
          <el-input size="large" clearable placeholder="请输入邮箱" v-model.trim="formData.email">
            <template #prefix>
              <span class="iconfont icon-account"></span>
            </template>
          </el-input>
        </el-form-item>
        <div v-if="currentOpType == 0">
          <el-form-item prop="nickName">
            <el-input
              size="large"
              clearable
              placeholder="请输入昵称"
              v-model.trim="formData.nickName"
            >
              <template #prefix>
                <span class="iconfont icon-nickname"></span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              clearable
              size="large"
              show-password
              placeholder="请输入密码"
              v-model.trim="formData.password"
            >
              <template #prefix>
                <span class="iconfont icon-password"></span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="registerPassword">
            <el-input
              clearable
              size="large"
              show-password
              placeholder="请再次输入密码"
              v-model.trim="formData.registerPassword"
            >
              <template #prefix>
                <span class="iconfont icon-password"></span>
              </template>
            </el-input>
          </el-form-item>
        </div>
        <el-form-item prop="password" v-if="currentOpType == 1">
          <el-input
            clearable
            show-password
            size="large"
            placeholder="请输入密码"
            v-model.trim="formData.password"
          >
            <template #prefix>
              <span class="iconfont icon-password"></span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="checkCode">
          <div class="check-code-panel">
            <div class="input">
              <el-input
                size="large"
                clearable
                placeholder="请输入验证码"
                v-model.trim="formData.checkCode"
              >
                <template #prefix>
                  <span class="iconfont icon-checkcode"></span>
                </template>
              </el-input>
            </div>
            <div class="code-img" @click="getCheckCodeInfo">
              <img :src="checkCodeInfo?.checkCode" alt="" />
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="width: 100%" @click="submitForm()">
            <span v-if="currentOpType == 1">登录</span>
            <span v-if="currentOpType == 0">注册</span>
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </commonDialog>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useFormRules } from '@/utils/rules'
import type { FormInstance, FormRules } from 'element-plus'
import { useHomeStore } from '@/stores/home'
import { getCodeApi, loginHttpRequest, registerHttpRequest } from '@/services/api/home'
import message from '@/utils/message'
interface LoginData {
  email: string
  password: string
  checkCode: string
  checkCodeKey: string
}

interface RegisterData extends LoginData {
  nickName: string
}

const homeStore = useHomeStore()

const dialogConfig = ref({
  buttons: []
})

// 表单数据
const formData = ref({
  email: '',
  password: '',
  checkCode: '',
  nickName: '',
  registerPassword: ''
})

//获取验证码
const checkCodeInfo = ref<{
  checkCode: string
  checkCodeKey: string
}>()
const getCheckCodeInfo = async () => {
  const codeInfo = await getCodeApi()
  checkCodeInfo.value = codeInfo.data
}
onMounted(() => {
  getCheckCodeInfo()
})
//验证规则
const { emailRule, passwordRule, confirmPasswordRule, checkCodeRule, nickNameRule } =
  useFormRules(formData)

const formDataRef = ref()

// 动态生成rules
const rules = ref<FormRules>({
  email: emailRule,
  password: passwordRule,
  registerPassword: confirmPasswordRule('password'), // 关联password字段
  checkCode: checkCodeRule,
  nickName: nickNameRule
})

//切换注册或者登录面板
const currentOpType = ref(1)
const showPanel = (opType: number) => {
  formDataRef.value?.resetFields()
  getCheckCodeInfo()
  currentOpType.value = opType
  if (opType === 1) {
    // 登录时移除注册字段的校验
    delete rules.value.nickName
    delete rules.value.registerPassword
  } else {
    // 注册时添加校验
    rules.value.nickName = nickNameRule
    rules.value.registerPassword = confirmPasswordRule('password')
  }
}

// 表单提交
const submitForm = () => {
  formDataRef.value.validate(async (valid: any) => {
    if (!valid) return
    //获取表单数据
    const data = getSubmitData()
    //登录和注册
    const result =
      currentOpType.value == 1
        ? await loginHttpRequest({ ...data })
        : await registerHttpRequest({ ...(data as RegisterData) })
    if (currentOpType.value == 0) {
      message.success('注册成功')
      showPanel(1)
    } else {
      message.success('登录成功')
      homeStore.setLogin(false)
      homeStore.saveUserInfo(result.data)
    }
    getCheckCodeInfo()
    formDataRef.value?.resetFields()
  })
}

//获取当前需要提交的表单数据
const getSubmitData = (): LoginData | RegisterData => {
  const base = {
    email: formData.value.email,
    password: formData.value.password,
    checkCode: formData.value.checkCode,
    checkCodeKey: checkCodeInfo.value?.checkCodeKey || ''
  }

  return currentOpType.value === 1 ? base : { ...base, nickName: formData.value.nickName }
}

//关闭弹窗
const closeDialog = () => {
  homeStore.setLogin(false)
}
</script>

<style lang="less" scoped>
.dialog-panel {
  display: flex;
  align-items: center;
  justify-content: space-around;
  .bg {
    width: 450px;
    height: 580px;
    overflow: hidden;
    img {
      width: 100%;
    }
  }

  .login-register {
    width: 350px;
    .tab-panel {
      margin: 10px auto;
      display: flex;
      width: 130px;
      font-size: 18px;
      align-items: center;
      justify-content: space-around;
      cursor: pointer;
      .active {
        color: var(--blue2);
      }
    }
    .no-account {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
    .login-btn {
      width: 100%;
    }
    .bottom-btn {
      margin-bottom: 0px;
    }
  }
}

.check-code-panel {
  display: flex;
  align-items: center;
  width: 100%;
  .input {
    flex: 2;
  }
  .code-img {
    flex: 1;
    img {
      vertical-align: middle;
      cursor: pointer;
    }
  }
  .right-panel {
    margin-left: 5px;
    cursor: pointer;
  }
}
</style>
